import { Space, Table, Tag, Input, Button, Popover, Avatar, Modal, Form, message, Radio, Popconfirm } from 'antd';
import type { RadioChangeEvent, TableProps } from 'antd';
import { EditFilled, DeleteFilled, PlusSquareFilled, QqOutlined } from "@ant-design/icons"
import styles from "./index.module.scss"
import { HappyProvider } from '@ant-design/happy-work-theme';
import { findAlluser } from "@/apis/admin/admin"
import { useEffect, useState } from 'react';
import { Admin_user, updateRole, deleteone } from "@/apis/admin/admin"
import dayjs from 'dayjs';
const base_url = import.meta.env.VITE_APP_URL
interface DataType {
    _id: string
    username: string
    age: number
    role: string
    sex: string
    avatar?: string
    qqnumber?: string
    constellation?: string
}




type user = {
    avatar: string,
    brithday: string,
    constellation: string,
    role: string,
    sex: string,
    age: number,
    username: string,
    qqnumber: string,
    _id: string
}
const FormatAge = (data: user[]) => {
    const age = (brith: string) => {
        return Number(dayjs(Date.now()).format("YYYY-MM-DD").split("-")[0]) - Number(brith.split("-")[0])
    }
    data.map((item: user) => {
        item.age = age(item.brithday)

    })
    return data
}
const Users = () => {
    const [form] = Form.useForm()
    const [datalist, setdatalist] = useState<user[]>([])
    const [isModalOpen, setIsopen] = useState(false)
    const [Currentpage, setCurrentpage] = useState<number>(1)
    const [total, settotal] = useState(0)
    const [role, setrole] = useState("3")
    const [keyowrd, setkeyword] = useState('')
    const [open, setOpen] = useState<string>('')
    const [value, setValue] = useState('2');

    //修改限权-----start-----------
    const hide = async (type: string, id: string) => {
        if (type === 'cancel') {
            setOpen('')
        } else {
            const res = await updateRole({ id, role: value })
            if (res.status === 200) {
                message.success("修改成功")
                Getall(Currentpage * 5 - 5, role)
                setOpen('')
            }
        }
    };

    const handleOpenChange = (id: string) => {
        if (id === open) {
            setOpen('')
        } else {
            setOpen(id)

        }
    };
    //修改限权-----end-----------
    //获取用户列表------------start-----------
    const Getall = async (skip: number, role: string) => {
        const res: any = await findAlluser(skip, role, keyowrd)
        console.log(res.data)

        settotal(res.count[0] ? res.count[0].total : 0)
        setdatalist([...FormatAge(res.data)])
    }
    //获取用户列表---------------end--------------

    //添加用户--------start-----------
    const handleOk = async () => {
        try {
            const vali = await form.validateFields()
            const res = await Admin_user(vali)
            if (res.status === 200) {
                message.success("添加成功")
                form.resetFields()
                setIsopen(false)
                // setCurrentpage(1)
                Getall(Currentpage * 5 - 5, role)
            }

        } catch (error) {

        }

    }
    const handleCancel = () => {
        setIsopen(false)
    }
    //添加用户-----end---------

    //删除------start--------
    const confirm = async (e: any) => {
        const res = await deleteone(e)
        if (res.status === 200) {
            message.success("删除成功")
            console.log(datalist.length, Currentpage)
            if (Currentpage !== 1 && datalist.length == 1) {
                setCurrentpage(Currentpage - 1)

            } else {
                Getall(Currentpage * 5 - 5, role)
            }
        };
    }
    const cancel = (e: any) => {
        e
    };
    //删除------end-------------
    const columns: TableProps<DataType>['columns'] = [
        {
            title: '用户名',
            dataIndex: 'username',
            render: (_, text) => {
                return <Popover content={<div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
                    <Avatar src={base_url + text.avatar}></Avatar>
                    <span>{text.constellation}</span>
                    <span>{text.qqnumber}</span>
                </div>} title="其他信息">
                    <a>{_}
                    </a>
                </Popover>


            },
        },
        {
            title: '年龄',
            dataIndex: 'age',
        },
        {
            title: '性别',
            dataIndex: 'sex',

            render: (_, { sex }) => {
                return <>
                    {
                        sex === 'male' ? "男" : "女"
                    }
                </>
            }
        },
        {
            title: '出生日期',
            dataIndex: 'brithday',
        },
        {
            title: '角色',
            dataIndex: 'role',
            render: (_, { role }) => {
                let premiss = ''
                let color = ''
                switch (role) {
                    case "0":
                        premiss = "超级管理员"
                        color = 'red'
                        break;
                    case "1":
                        premiss = "管理员"
                        color = 'blue'
                        break;
                    case "2":
                        premiss = "普通用户"
                        color = 'green'
                        break;
                    default:
                        break;
                }
                return (
                    <>

                        <Tag color={color} >
                            {premiss}
                        </Tag>
                    </>
                )
            }
        },
        {
            title: '操作',
            render: (_) => {
                return (
                    <Space size="middle">
                        <HappyProvider>
                            <Popover content={<div>
                                <Radio.Group onChange={onChange} value={value} style={{ margin: "5px 0" }}>
                                    <Radio value={'0'}>超级管理员</Radio>
                                    <Radio value={'1'}>管理员</Radio>
                                    <Radio value={'2'}>普通用户</Radio>
                                </Radio.Group>
                                <div style={{ display: "flex", justifyContent: "space-evenly" }}>
                                    <Button onClick={() => hide('cancel', '')}>取消</Button>
                                    <Button type='primary' onClick={() => hide('ok', _._id)}>修改</Button>
                                </div>
                            </div>}
                                title={_.username + ':角色'}
                                trigger="click"
                                open={open === _._id ? true : false}
                                onOpenChange={() => handleOpenChange(_._id)}
                            >
                                <Button type="dashed" icon={<EditFilled />}></Button>

                            </Popover>
                        </HappyProvider>

                        <HappyProvider>
                            <Popconfirm
                                title={"删除用户：" + _.username}
                                description="确定删除吗?"

                                onConfirm={() => confirm(_._id)}
                                onCancel={cancel}
                                okText="确认"
                                cancelText="取消"
                            >
                                <Button type="dashed" icon={<DeleteFilled style={{ color: 'red' }} />}></Button>

                            </Popconfirm>
                        </HappyProvider>
                    </Space>
                )
            }
        },
    ];
    const onChange = (e: RadioChangeEvent) => {
        setValue(e.target.value);
    };

    useEffect(() => {
        Getall(Currentpage * 5 - 5, role)
    }, [Currentpage, role])
    const validatePhone = (_: any, value: string) => {
        const phoneRegex = /^\d{6,10}$/;
        if (!phoneRegex.test(value)) {
            return Promise.reject('请输入6-10位数字!');
        }
        return Promise.resolve();
    };
    const search = async () => {
        setCurrentpage(1)
        setrole('3')
        Getall(0, '3')
    }
    return (

        <div className={styles.Users}>
            <div className={styles.top}>
                <div className={styles.left}>
                    <Input value={keyowrd} onChange={(e) => { setkeyword(e.target.value) }} />
                    <HappyProvider>
                        <Button type="primary" onClick={search} style={{ marginLeft: "10px" }} >搜索</Button>
                    </HappyProvider>
                    <HappyProvider>
                        <Button type={role === '3' ? 'dashed' : "primary"} onClick={() => {
                            setCurrentpage(1)
                            setrole('3')
                        }} style={{ marginLeft: "10px" }} >全部</Button>
                    </HappyProvider>
                    <HappyProvider>
                        <Button type={role === '0' ? 'dashed' : "primary"} onClick={() => {
                            setCurrentpage(1)
                            setrole('0')
                        }} style={{ marginLeft: "10px" }}  >超级管理员</Button>
                    </HappyProvider>
                    <HappyProvider>
                        <Button type={role === '1' ? 'dashed' : "primary"} onClick={() => {
                            setCurrentpage(1)
                            setrole('1')
                        }} style={{ marginLeft: "10px" }} >管理员</Button>
                    </HappyProvider>
                    <HappyProvider>
                        <Button type={role === '2' ? 'dashed' : "primary"} onClick={() => {
                            setCurrentpage(1)
                            setrole('2')
                        }} style={{ marginLeft: "10px" }} >普通用户</Button>
                    </HappyProvider>
                </div>
                <div className={styles.right}>

                    <HappyProvider>
                        <Button onClick={() => setIsopen(true)} type="primary" style={{ marginLeft: "10px" }} icon={<PlusSquareFilled />}></Button>
                    </HappyProvider>

                </div>
            </div>


            {/* 添加用户 */}
            <Modal title="添加" open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
                <Form form={form} labelCol={{ span: 5 }} wrapperCol={{ span: 19 }} >
                    <Form.Item label="用户名" name="username"
                        rules={[{ required: true, message: '长度在2-7', max: 7, min: 2 }]}
                    >
                        <Input autoComplete={"off"} placeholder="请输入用户名" />
                    </Form.Item>
                    <Form.Item label="密码" name="password"
                        rules={[{ required: true, message: '至少三位', min: 3 }]}
                    >
                        <Input.Password autoComplete="off" placeholder="请输入密码" />
                    </Form.Item>
                    <Form.Item label="qq" name="qqnumber"

                        rules={[{ required: true, message: "" }, {
                            validator: validatePhone,
                        },]}
                    >
                        <Input prefix={<QqOutlined className="site-form-item-icon" />} />
                    </Form.Item>
                </Form>

            </Modal>
            {/* 添用户 */}
            <Table rowKey={'_id'} columns={columns} dataSource={datalist} pagination={{
                showTotal: () => {
                    return `共${total}条`
                },
                current: Currentpage,
                defaultCurrent: 1,
                total: total,
                defaultPageSize: 5,
                showSizeChanger: false,
                onChange: (page) => {
                    setCurrentpage(page)
                }

            }} />
        </div>
    )
}

export default Users;